package com.example.aircraftwar.codes.application.music;

import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.Binder;
import android.os.IBinder;

import com.example.aircraftwar.R;

import java.util.HashMap;

public class SoundService extends Service {
    private HashMap<Integer, Integer> soundID = new HashMap<Integer, Integer>();
    private SoundPool mSoundPool;
    private MediaPlayer player;
    private boolean videoOpen;
    public SoundService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mSoundPool = new SoundPool(4, AudioManager.STREAM_SYSTEM, 5);
        soundID.put(1, mSoundPool.load(this, R.raw.bullet_hit, 1));
        soundID.put(2, mSoundPool.load(this, R.raw.get_supply, 1));
        soundID.put(3, mSoundPool.load(this, R.raw.bomb_explosion, 1));
        soundID.put(4, mSoundPool.load(this, R.raw.game_over, 1));
    }

    @Override
    public IBinder onBind(Intent intent){
        videoOpen = intent.getBooleanExtra("videoOpen",false);
        return new MyBinder();
    }

    public class MyBinder extends Binder {
        public void playBullet(){
            if(videoOpen){
                mSoundPool.play(soundID.get(1), 1, 1, 0,0,1);
            }
        }
        public void playSupply(){
            if(videoOpen){
                mSoundPool.play(soundID.get(2), 1, 1, 0, 0, 1);
            }
        }
        public void playBomb(){
            if(videoOpen){
                mSoundPool.play(soundID.get(3), 1, 1, 0, 0, 1);
            }
        }
        public void playGameOver(){
            if(videoOpen){
                mSoundPool.play(soundID.get(4), 1, 1, 0, 0, 1);
            }
        }
    }

    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopMusic();
    }

    public void stopMusic() {
        if (player != null) {
            player.stop();
            player.reset();//重置
            player.release();//释放
            player = null;
        }
    }
}